using System.Xml;
using System.IO;
using System.Windows.Forms;
using System;
using BlimpControlPanel;
using System.IO.Ports;
using System.Collections;

class xmlParsing
{
    string nwlUpdateFilename = @"C:\test.kml";

    public void saveKMLNetworkLinkCoordinates(double latitude, double longitude, double altitude)
    {
      XmlTextWriter xmlWriter = null;

      try
      {
         if (File.Exists(nwlUpdateFilename))
         {
            FileAttributes attr = File.GetAttributes(nwlUpdateFilename);

             if((attr & FileAttributes.ReadOnly) != FileAttributes.ReadOnly)
                File.Delete(nwlUpdateFilename);
         }
         else
         {
            Stream fStream = File.Create(nwlUpdateFilename);
            fStream.Close();
         }

         xmlWriter = new XmlTextWriter(nwlUpdateFilename, System.Text.Encoding.UTF8);
         xmlWriter.Indentation = 4;
         xmlWriter.IndentChar = ' ';
         xmlWriter.Formatting = Formatting.Indented;

         xmlWriter.WriteStartDocument();
         xmlWriter.WriteStartElement("kml");
         xmlWriter.WriteAttributeString("xmlns", "http://www.opengis.net/kml/2.2");
         xmlWriter.WriteStartElement("Placemark");
         WriteXmlElement("name", "Current Location", xmlWriter);
         xmlWriter.WriteStartElement("Point");

         string latLongAltString = longitude.ToString() + "," + latitude.ToString() + "," + altitude.ToString();

         WriteXmlElement("coordinates", latLongAltString, xmlWriter);
         
         xmlWriter.WriteEndElement(); // End point
         xmlWriter.WriteEndElement(); // End placemark
         xmlWriter.WriteEndElement(); // End kml
      }
      catch (Exception e)
      {
         MessageBox.Show(e.Message);
      }
      finally
      {
         if (xmlWriter != null)
         {
            xmlWriter.WriteEndDocument();
            xmlWriter.Close();
         }
      }
}

   public void saveKMLData(string fileName, string pathName, ArrayList latLongAltArray, ProgressBar p, bool savePathFile)
   {
      DialogResult dialog = DialogResult.Retry;
      XmlTextWriter xmlWriter = null;

      try
      {
         if (File.Exists(fileName))
         {
            FileAttributes attr = File.GetAttributes(fileName);

            while ((attr & FileAttributes.ReadOnly) == FileAttributes.ReadOnly && dialog == DialogResult.Retry)
            {
               dialog = MessageBox.Show(fileName + " Read-Only.  " + Environment.NewLine +
                                        "Retry or Cancel?", "File Read-Only",
                                        MessageBoxButtons.RetryCancel, MessageBoxIcon.Question);

               attr = File.GetAttributes(fileName);
            }

            if (dialog == DialogResult.Cancel)
               return;
         }
         else
         {
            Stream fStream = File.Create(fileName);
            fStream.Close();
         }

         xmlWriter = new XmlTextWriter(fileName, System.Text.Encoding.UTF8);

         p.Value = p.Value + 5;
         xmlWriter.Indentation = 4;
         xmlWriter.IndentChar = ' ';
         xmlWriter.Formatting = Formatting.Indented;

         xmlWriter.WriteStartDocument();
         xmlWriter.WriteStartElement("kml");
         xmlWriter.WriteAttributeString("xmlns", "http://earth.google.com/kml/2.2");
         xmlWriter.WriteStartElement("Document");
         WriteXmlElement("name", pathName, xmlWriter);
         WriteXmlElement("description", "Path of the blimp.", xmlWriter);

         if (!savePathFile)
         {
            WriteIconElement(xmlWriter, "paddle-a", "http://maps.google.com/mapfiles/kml/paddle/A.png", "32", "1");
            WriteStyleElement(xmlWriter);
         }

         WritePathElements(xmlWriter, latLongAltArray, "paddle-a", savePathFile);
         WritePathElements(xmlWriter, latLongAltArray, "paddle-a", true);

         xmlWriter.WriteEndElement(); // End document
         xmlWriter.WriteEndElement(); // End kml
      }
      catch (Exception e)
      {
         MessageBox.Show(e.Message);
      }
      finally
      {
         if (xmlWriter != null && dialog != DialogResult.Cancel)
         {
            xmlWriter.WriteEndDocument();
            xmlWriter.Close();
         }
      }
   }

   private void WriteIconElement(XmlTextWriter xmlWriter, string iconName, string href, string xSize, string ySize)
   {
      xmlWriter.WriteStartElement("Style");
      xmlWriter.WriteAttributeString("id", iconName);
      xmlWriter.WriteStartElement("IconStyle");
      xmlWriter.WriteStartElement("Icon");
      xmlWriter.WriteStartElement("href");
      xmlWriter.WriteString(href);
      xmlWriter.WriteEndElement(); // End href
      xmlWriter.WriteEndElement(); // End Icon
      xmlWriter.WriteStartElement("hotSpot");
      xmlWriter.WriteAttributeString("x", xSize);
      xmlWriter.WriteAttributeString("y", ySize);
      xmlWriter.WriteAttributeString("xunits", "pixels");
      xmlWriter.WriteAttributeString("yunits", "pixels");
      xmlWriter.WriteEndElement(); // End hotSpot
      xmlWriter.WriteEndElement(); // End IconStyle
      xmlWriter.WriteEndElement(); // End Style

   }

   private void WritePathElements(XmlTextWriter xmlWriter, ArrayList latLongAltArray, string iconName, bool savePathFile)
   {
       if (savePathFile)
       {
           xmlWriter.WriteStartElement("Placemark");
           WriteXmlElement("name", "Extruded Path", xmlWriter);
           WriteStyleURL(xmlWriter, "yellowLineGreenPoly");
           WriteXmlElement("description", "Extruded path of the blimp.", xmlWriter);
           xmlWriter.WriteStartElement("LineString");
           //WriteXmlElement("extrude", "1", xmlWriter);
           WriteXmlElement("tessellate", "1", xmlWriter);
       }
       else
       {
           WriteXmlElement("altitudeMode", "absolute", xmlWriter);
       }

       WriteCoordinates(xmlWriter, latLongAltArray, iconName, savePathFile);

      if (savePathFile) {
         xmlWriter.WriteEndElement(); // End LineString
         xmlWriter.WriteEndElement(); // End Placemark
      }
   }

   private static void WriteStyleURL(XmlTextWriter xmlWriter, string styleURL)
   {
       xmlWriter.WriteStartElement("styleUrl");
       xmlWriter.WriteString("#" + styleURL);
       xmlWriter.WriteEndElement(); // End styleUrl
   }

   private void WriteCoordinates(XmlTextWriter xmlWriter, ArrayList latLongAltArray, string iconName, bool savePathFile)
   {
      if (savePathFile)
         xmlWriter.WriteStartElement("coordinates");

      foreach (string str in latLongAltArray)
         WriteTimePlaceMarker(xmlWriter, str, iconName, savePathFile);

      if(savePathFile)
         xmlWriter.WriteEndElement(); // End coordinates
   }

   private int pointNumber = 0;

   private void WriteTimePlaceMarker(XmlTextWriter xmlWriter, string str, string iconName, bool savePathFile)
   {
      if (savePathFile)
      {
         xmlWriter.WriteString(GetCoordinatesFromGPSData(str));
         xmlWriter.WriteString(Environment.NewLine);
      }
      else
      {
         xmlWriter.WriteStartElement("Placemark");

         WritePointDescription(xmlWriter, "Point" + (pointNumber++).ToString());
         WriteTimeStamp(xmlWriter, str);
         WriteStyleURL(xmlWriter, iconName);
         WritePoint(xmlWriter, str);
         xmlWriter.WriteEndElement(); // End Placemark
      }
   }

   private void WritePointDescription(XmlTextWriter xmlWriter, string pointDescription)
   {
         xmlWriter.WriteStartElement("description");
         xmlWriter.WriteString(pointDescription);
         xmlWriter.WriteEndElement();
   }

   private static void WritePoint(XmlTextWriter xmlWriter, string str)
   {
      xmlWriter.WriteStartElement("Point");
      WriteCoordinates(xmlWriter, str);
      xmlWriter.WriteEndElement(); // End Point
   }

   private static void WriteCoordinates(XmlTextWriter xmlWriter, string str)
   {
      xmlWriter.WriteStartElement("coordinates");
      xmlWriter.WriteString(GetCoordinatesFromGPSData(str));
      xmlWriter.WriteEndElement(); // End coordinates
   }

   private static string GetCoordinatesFromGPSData(string str)
   {
      string[] data = str.Split(new char[] { ',' });

      return data[2].Trim() + "," + data[3].Trim() + "," + data[4].Trim();
   }

   private void WriteTimeStamp(XmlTextWriter xmlWriter, string str)
   {
      xmlWriter.WriteStartElement("TimeStamp");
      xmlWriter.WriteStartElement("when");
      xmlWriter.WriteString(GetDateTimeStringFromGPSData(str));
      xmlWriter.WriteEndElement(); // End when
      xmlWriter.WriteEndElement(); // End TimeStamp
   }

   int lastMin = 0;
   int lastHour = 0;

   private string GetDateTimeStringFromGPSData(string str)
   {
      string[] data = str.Split(new char[] { ',' });
      string timeString = "";
      string dateString = "";

      foreach (string dataStr in data)
      {
         if (dataStr.Contains(":"))
            timeString = dataStr.Trim();
         else if (dataStr.Contains("/"))
         {
            string[] date = dataStr.Split('/');
            dateString = "20" + date[2].Trim() + "-" + date[0].Trim() + "-" + date[1].Trim();
         }
      }

      lastMin++;

      if (lastMin >= 60)
      {
          lastHour++;
          lastMin = 0;
      }

      return "2000-00-00T" + lastHour.ToString("00") + ":" + lastMin.ToString("00") + ":00";
      //if (dateString != "" && timeString != "")
      //   return dateString + "T" + timeString + "Z";
      //else
      //   return "";

   }

   private static void WriteStyleElement(XmlTextWriter xmlWriter)
   {
      xmlWriter.WriteStartElement("Style");

      xmlWriter.WriteAttributeString("id", "yellowLineGreenPoly");

      WriteLineStyle(xmlWriter);
      WritePolyStyle(xmlWriter);

      xmlWriter.WriteEndElement(); // End Style
   }

   private static void WritePolyStyle(XmlTextWriter xmlWriter)
   {
      xmlWriter.WriteStartElement("PolyStyle");
      WriteXmlElement("color", "7fFFFF00", xmlWriter);
      xmlWriter.WriteEndElement(); // End PolyStyle
   }

   private static void WriteLineStyle(XmlTextWriter xmlWriter)
   {
      xmlWriter.WriteStartElement("LineStyle");
      WriteXmlElement("color", "7fFFFF00", xmlWriter);
      WriteXmlElement("width", "4", xmlWriter);
      xmlWriter.WriteEndElement(); // End LineStyle

   }

   private static void WriteXmlElement(String elementName, String value, XmlTextWriter xmlWriter)
   {
      xmlWriter.WriteStartElement(elementName);
      xmlWriter.WriteString(value);
      xmlWriter.WriteEndElement();
   }

}
